package com.example.administrator.appstpremvpdemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.administrator.appstpremvpdemo.common.Constances;
import com.example.administrator.appstpremvpdemo.model.entity.ValueBean;
import com.example.administrator.appstpremvpdemo.util.SdUtils;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/5.
 */

public class DownloadService extends Service {

    public int getProgress() {
        return mProgress;
    }

    public int mProgress = 0;

    /**
     * 下载任务列表。
     */
    private Map<String, DownloadRequest> mDownloadRequests = new HashMap<>();

    /**
     * 下载任务
     */
    public void startDownLoad(ValueBean datebean, int flags) {
        String path = datebean.getApk();
        Log.w("DownloadService", path.toString());
        Log.w("DownloadService", flags + "");
        DownloadRequest downloadRequest = NoHttp.createDownloadRequest(path,
                RequestMethod.GET, SdUtils.getSDPath(), "appId:" + flags + ".apk", true, true);
        mDownloadRequests.put(path, downloadRequest);
        NoHttp.getDownloadQueueInstance().add(flags, mDownloadRequests.get(path), mDownloadListener);

        Log.w("DownloadService", "mDownloadRequests.size():" + mDownloadRequests.size());
    }

    private DownloadListener mDownloadListener = new DownloadListener() {
        @Override
        public void onDownloadError(int what, Exception exception) {
            mOnStatusChangeListener.onStatusChange(what, Constances.DOWNLOAD_ERRO);
        }

        @Override
        public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {
            Log.d("DownloadService", what + "-/-rangeSize"+rangeSize);

            mOnStatusChangeListener.onStatusChange(what, Constances.DOWNLOAD_START);
        }

        @Override
        public void onProgress(int what, int progress, long fileCount, long speed) {
            Log.d("DownloadService", what + "-/-onProgress"+progress);
            onProgressListener.onprogress(what, progress);
            mOnStatusChangeListener.onStatusChange(what, Constances.DOWNLOAD_ING);
        }

        @Override
        public void onFinish(int what, String filePath) {
            Log.d("DownloadService", what + "-/-onFinish:" + filePath);
            mOnStatusChangeListener.onStatusChange(what, Constances.DOWNLOAD_FINISH);
        }

        @Override
        public void onCancel(int what) {
            Log.d("DownloadService", what + "-/-onCancel:");
            mOnStatusChangeListener.onStatusChange(what, Constances.DOWNLOAD_CANCEL);
        }
    };

    /**
     * 暂停下载，如果服务器返回code是206则说明服务器支持添加range的方式进行断点下载
     * 否则就得执行重新下载（删除已有文件后重新下载）
     * @param path
     */
    public void cancelWhatrequest(String path) {
        DownloadRequest downloadRequest = mDownloadRequests.get(path);
        if (downloadRequest != null) {
            downloadRequest.cancel();
        }
    }

    /**
     * 返回一个Binder对象
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new DownloadBinder();
    }

    public class DownloadBinder extends Binder {
        /**
         * 获取当前Service的实例
         *
         * @return
         */
        public DownloadService getService() {
            return DownloadService.this;
        }
    }


    /**
     * 更新下载状态的回调接口
     */
    public interface onStatusChangeListener {

        void onStatusChange(int what, String status);

    }

    private onStatusChangeListener mOnStatusChangeListener;

    public void setOnStatusChangeListener(onStatusChangeListener onStatusChangeListener) {
        mOnStatusChangeListener = onStatusChangeListener;
    }


    /**
     * 更新进度的回调接口
     */
    public interface OnProgressListener {

        void onprogress(int what, int progress);
    }

    private OnProgressListener onProgressListener;

    /**
     * 注册回调接口的方法，供外部调用
     *
     * @param onProgressListener
     */
    public void setOnProgressListener(OnProgressListener onProgressListener) {
        this.onProgressListener = onProgressListener;
    }

}
